<template>
  <div class="app-container">
    <el-card class="box-card">
      <div>
        <el-button type="primary" size="small" @click="addClick">
          <i class="el-icon-circle-plus-outline"></i>增加
        </el-button>
        <el-button
          type="danger"
          size="small"
          :disabled="!multipleSelection.length"
          @click="deBounceWrap(delClick, multipleSelection)"
        >
          <i class="el-icon-delete"></i>删除
        </el-button>
      </div>
      <div class="flex mt-3">
        <el-date-picker
          v-model="form.expire_date"
          style="width: 15%"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="到期时间"
        ></el-date-picker>
        <el-select
          v-model="form.cate1_id"
          placeholder="请选择靓号类别"
          class="ml-3"
          @change="parentChange"
          style="width: 15%"
        >
          <el-option
            v-for="item in parentList"
            :label="item.title"
            :key="item.id"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
      <div class="flex mt-3">
        <el-select
          v-model="form.status"
          placeholder="请选择靓号状态"
          style="width: 15%"
        >
          <el-option
            v-for="item in statusOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="form.cate2_id"
          placeholder="请选择二级类别"
          class="ml-3"
          style="width: 15%"
        >
          <el-option
            v-for="item in liangChildList"
            :label="item.title"
            :key="item.id"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-input
          v-model="form.good_code"
          placeholder="请输入靓号"
          class="ml-3"
          style="width: 15%"
        ></el-input>
        <el-date-picker
          v-model="form.add_date"
          style="width: 15%"
          class="ml-3"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="上架时间"
        >
        </el-date-picker>
        <el-input
          v-model="form.price"
          placeholder="请输入价格"
          class="ml-3"
          style="width: 15%"
        ></el-input>
        <div class="ml-4 flex items-center" style="width: 17%">
          <i
            @click="handleSearch"
            class="el-icon-search p-1 text-white text-2xl bg-green-500 cursor-pointer"
          ></i>
          <i
            @click="resetClick"
            class="el-icon-refresh p-1 ml-3 text-white text-2xl bg-red-500 cursor-pointer"
          ></i>
        </div>
      </div>

      <el-table
        ref="multipleTable"
        :data="tableData"
        stripe
        class="mt-3"
        tooltip-effect="dark"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="checkBoxDisable"
        ></el-table-column>
        <el-table-column prop="id" label="序号"></el-table-column>
        <el-table-column
          prop="product_name"
          label="靓号"
          width="120"
        ></el-table-column>
        <el-table-column prop="cate1_name" label="靓号类别"></el-table-column>
        <el-table-column prop="cate2_name" label="二级分类"></el-table-column>

        <el-table-column prop="product_price" label="靓号价格">
          <template slot-scope="scope">
            <div class="flex flex-col">
              <span v-for="(item,index) in scope.row.product_price" :key="index">
                <p>
                  {{ item.day === 9999 ? "永久" : item.day + "天" }} ：{{
                    item.price
                  }}金币
                </p>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="add_time" label="上架时间"></el-table-column>
        <el-table-column prop="on_sale" label="靓号状态">
          <template slot-scope="scope">
            <!-- <span>{{ statusChang(scope.row.on_sale) }}</span> -->
            <el-tag v-if="scope.row.on_sale === 1" type="success">上架</el-tag>
            <el-tag v-else-if="scope.row.on_sale === 2" type="danger"
              >下架</el-tag
            >
            <el-tag v-else type="primary">使用中</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="expire_time" label="到期时间"></el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="240">
          <template slot-scope="scope">
            <el-button
              type="success"
              size="mini"
              @click="editClick(scope.row)"
              plain
            >
              <i class="el-icon-edit-outline"></i>编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="giveClick(scope.row)"
              plain
            >
              <i class="el-icon-present"></i>赠送
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deBounceWrap(delClick, [scope.row])"
              plain
            >
              <i class="el-icon-delete"></i>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <TMPagination
        :current-page.sync="pageList.page"
        :total.sync="pageList.total"
        :page-size.sync="pageList.page_size"
        @updateTable="getTableData"
      />

      <add-edit-modal
        :status.sync="addEditModal.status"
        :parent-list="parentList"
        @updateTable="getTableData"
        :dialog-visible.sync="addEditModal.visible"
        :detail="addEditModal.detail"
      />

      <giveAwayModal
        :dialog-visible.sync="giveAwayModal.visible"
        :detail="giveAwayModal.detail"
      />
    </el-card>
  </div>
</template>

<script>
import TMPagination from "../../wishList/childComps/TMPagination/TMPagination";
import addEditModal from "./childComps/addEditModal/addEditModal";
import giveAwayModal from "./childComps/giveAwayModal/giveAwayModal";

import { prettyPoolData } from "../../../../api/personalizedMall/goodNumberPool";
import { categoryDropDownBox } from "../../../../api/personalizedMall/goodNumberRecord";
import { delCommodity } from "../../../../api/personalizedMall/activeCommodities";

export default {
  name: "goodNumberPool",
  components: {
    addEditModal,
    giveAwayModal,
    TMPagination
  },
  data() {
    return {
      loading: false,
      giveAwayModal: {
        visible: false,
        detail: {}
      },
      addEditModal: {
        visible: false,
        status: "Add",
        detail: {}
      },
      multipleSelection: [],
      form: {
        cate1_id: null, // 父分类id，0：不限制，其它的根据接口
        cate2_id: null, // 子分类id，0：不限制，其它的根据接口
        expire_date: null, // 过期日期，yyyy-mm-dd
        status: null, // 出售状态：0：不限制（默认）；1：上架；2：下架；3：使用中
        good_code: null, // 靓号
        price: null, // 价格
        add_date: null // 上架日期，yyyy-mm-dd
      },
      statusOption: [
        { label: "上架", value: 1 },
        { label: "下架", value: 2 }
      ],
      parentList: [],
      liangChildList: [],
      tableData: [],
      pageList: {
        page: 1,
        page_size: 10,
        total: 10
      },
      order: {
        addTimeOrder: null,
        expireTime: null
      }
    };
  },
  created() {
    this.getDownList();
    this.getTableData();
  },
  methods: {
    // 点击事件
    /**
     * addClick
     * @desc 点击新增 按钮
     */
    addClick() {
      this.addEditModal.status = "Add";
      this.addEditModal.visible = true;
    },
    sortClick(obj) {
      if (obj.prop === "add_time" && obj.order) {
        this.order.addTimeOrder = obj.order === "ascending" ? 0 : 1;
      } else this.order.addTimeOrder = null;

      if (obj.prop === "expire_time" && obj.order) {
        this.order.expireTime = obj.order === "ascending" ? 0 : 1;
      } else this.order.expireTime = null;
      this.getTableData();
    },
    /**
     * editClick
     * @desc 编辑按钮发生点击
     */
    editClick(detail) {
      this.addEditModal.detail = detail;
      this.addEditModal.status = "Edit";
      this.addEditModal.visible = true;
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    /**
     * delClick
     * @desc 点击删除按钮
     * @param idArr {Array} 行数据 [{}]
     */
    async delClick(idArr) {
      this.$confirm("此操作将删除数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let ids = "";
          idArr.map(
            (item, index) =>
              (ids += index === idArr.length - 1 ? item.id + "" : item.id + ",")
          );
          const detail = await delCommodity(ids);
          if (detail.code === 200) {
            this.$message({ type: "success", message: "删除成功!" });
            await this.getTableData();
          }
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除" });
        });
    },
    /**
     * giveClick
     * @desc 赠送按钮发生点击
     */
    giveClick(data) {
      this.giveAwayModal.detail = data;
      this.giveAwayModal.visible = true;
    },
    /**
     * resetClick
     * @desc 重置按钮 点击事件
     */
    resetClick() {
      for (const argumentsKey in this.form) {
        this.form[argumentsKey] = null;
      }
      this.pageList = {
        page: 1,
        page_size: 10,
        total: 10
      };
      this.getTableData();
    },
    /**
     * checkBoxDisable
     * @desc 选择盒子被禁用
     * @param row 行
     * @returns {boolean}
     */
    checkBoxDisable(row) {
      if (row.name === "小明") {
        return false;
      } else {
        return true;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    statusChang(status) {
      switch (status) {
        case 1:
          return "上架";
        case 2:
          return "下架";
        case 3:
          return "使用中";
      }
    },
    // 网络请求
    /**
     * getTableData
     * @desc 获取表格数据
     */
    async getTableData() {
      // 默认值
      let form = {
        cate1_id: 0, // 父分类id，0：不限制，其它的根据接口
        cate2_id: 0, // 子分类id，0：不限制，其它的根据接口
        expire_date: null, // 过期日期，yyyy-mm-dd
        status: 0, // 出售状态：0：不限制（默认）；1：上架；2：下架；3：使用中
        good_code: null, // 靓号
        price: null, // 价格
        add_date: null, // 上架日期，yyyy-mm-dd,
        order_expire_time: this.order.expireTime,
        order_add_time: this.order.addTimeOrder
      };
      for (const formKey in this.form) {
        if (
          !(
            !this.form[formKey] &&
            typeof this.form[formKey] != "undefined" &&
            this.form[formKey] != 0
          ) &&
          this.form[formKey]
        ) {
          form[formKey] = this.form[formKey];
        }
      }
      this.loading = true;
      const detail = await prettyPoolData(form, {
        page_size: this.pageList.page_size,
        page: this.pageList.page
      });
      if (detail.code === 200) {
        this.tableData = detail.data.data;
        this.pageList.page = detail.data.current_page;
        this.pageList.total = detail.data.total;
        this.pageList.page_size = detail.data.per_page * 1;
        this.loading = false;
      }
    },
    handleSearch() {
      this.pageList.page = 1;
      this.getTableData();
    },
    /**
     * getDownList
     * @desc 获取下拉框的数据
     */
    async getDownList() {
      const detail = await categoryDropDownBox();
      if (detail.code === 200) {
        detail.data.map(item => this.parentList.push(item));
      }
    },
    // 数据改变
    /**
     * parentChange
     * @desc 当靓号类别的数据发生改变时, 改变二级列别的数据
     */
    parentChange(val) {
      this.form.cate2_id = null;
      this.parentList.map(item =>
        item.id === val ? (this.liangChildList = item.sub_cates) : null
      );
    }
  }
};
</script>

<style lang="scss" scoped></style>
